package com.ruoyi.template.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.mapper.SysMenuMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.template.domain.*;
import com.ruoyi.template.dto.TemplateDTO;
import com.ruoyi.template.dto.TemplateDetailDTO;
import com.ruoyi.template.dto.TemplateDetailRequest;
import com.ruoyi.template.dto.TemplateRequest;
import com.ruoyi.template.mapper.TemplateDetailMapper;
import com.ruoyi.template.mapper.TemplateMenusMapper;
import com.ruoyi.template.mapper.TemplateUserMapper;
import com.ruoyi.template.service.TemplateService;
import com.ruoyi.template.mapper.TemplateMapper;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TemplateServiceImpl extends ServiceImpl<TemplateMapper, Template>
    implements TemplateService{

    @Autowired
    private TemplateMapper templateMapper;
    @Autowired
    private TemplateDetailMapper templateDetailMapper;
    @Autowired
    private TemplateMenusMapper templateMenusMapper;
    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Autowired
    private TemplateUserMapper templateUserMapper;
    @Autowired
    private SysUserMapper sysUseMapperr;
    /**
     *审核管理-新增模板管理
     * @param templateRequest
     * @return
     */
    @Override
    @Transactional
    public int saveTemplate(TemplateRequest templateRequest, String userName) {

        //检查模板名称
        checkTemplateName(templateRequest);

        // 保存主表
        Template template = new Template(IdUtils.fastSimpleUUID(),templateRequest.getTemplateName(),
                userName,DateUtils.getNowDate(),null,null);
        int rows = templateMapper.insert(template);

        //新增模板明细
        insertTemplateDetail(templateRequest,template);

        //新增模板菜单关联表
        insertTemplateMenus(templateRequest,template);

        return rows;
    }
    /**
     * 查询模板列表
     */
    @Override
    public List<TemplateDTO> selectTemplateList(Template template) {
        String templateName = template.getTemplateName();
        String templateId = template.getId();

        return templateMapper.selectTemplateList(templateName,templateId);
    }
    /**
     * 获取模板详细信息
     */
    @Override
    public TemplateDTO getTemplateWithDetails(String templateId) {
        // 查询模板和详细信息
        List<TemplateDTO> templates = templateMapper.findTemplateWithDetails(templateId);
        if (templates.isEmpty()) {
            return null;
        }
        return templates.get(0);
    }
    /**
     *审核管理-修改模板
     * @param templateRequest
     * @return
     */
    @Override
    @Transactional
    public int updateTemplate(TemplateRequest templateRequest, String nickname) {
        //检查模板名称
        checkTemplateName(templateRequest);

        String templateId = templateRequest.getTemplateId();
        if(StringUtils.isEmpty(templateId)){
            throw new ServiceException("获取模板ID失败，请关闭页面重新点击修改");
        }
        Template template = templateMapper.selectById(templateId);
        template.setTemplateName(templateRequest.getTemplateName());
        template.setUpdateBy(nickname);
        template.setUpdateTime(DateUtils.getNowDate());
        int rows = templateMapper.updateById(template);

        //新增模板明细
        insertTemplateDetail(templateRequest,template);

        //新增模板菜单关联表
        insertTemplateMenus(templateRequest,template);

        return rows;
    }
    /**
     * 获取菜单列表（排除按钮）
     */
    @Override
    public List<SysMenu> selectMenuList(SysMenu menu) {
        return templateMapper.selectMenuList(menu);
    }

    /**
     *新增/修改指定用户
     * @param templateUser
     * @return
     */
    @Override
    public int saveTemplateUser(TemplateUser templateUser) {

        String userIds[] = templateUser.getUserId().split(",");
        String templateId = templateUser.getTemplateId() ;

        //校验用户和菜单是否已绑定其他模板
        checkTemplateUser(templateId,templateUser.getUserId());

        //删除原来的数据
        LambdaQueryWrapper<TemplateUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TemplateUser::getTemplateId,templateId);
        templateUserMapper.delete(queryWrapper);

        //插入数据
        for(String userId : userIds){
            SysUser sysUser = sysUseMapperr.selectUserByIdAndStatus(Long.valueOf(userId));
            SysUser su = sysUseMapperr.selectUserById(Long.valueOf(userId));
            if(sysUser == null){
                throw new ServiceException("用户【"+su.getNickName()+"】已经停用，请重新选择用户");
            }
            TemplateUser tu  = new TemplateUser(IdUtils.fastSimpleUUID(),templateId,userId);
            templateUserMapper.insert(tu);
        }
        return userIds.length;
    }
    /**
     *校验用户和菜单是否已绑定其他模板
     * @param templateId,userId
     * @return
     */
    private void checkTemplateUser(String templateId, String userId ) {

        //用户ID集合
        List<Long> userIds = Arrays.stream(userId.split(","))
                .map(String::trim)
                .map(s -> Long.parseLong(s.replaceFirst("^0+", "")))
                .collect(Collectors.toList());

        //菜单ID集合
        List<Long> menuIds = templateMapper.getMenuIdsByTemplateId(templateId);

        //校验用户和菜单是否已绑定其他模板
        validateBindings(userIds, menuIds, templateId);
    }
    /**
     *校验用户和菜单是否已绑定其他模板
     * @param userIds,menuIds
     * @return
     */
    private void validateBindings(List<Long> userIds, List<Long> menuIds, String templateId) {

        // 将用户ID和菜单ID组合成列表
        List<UserMenuBinding> bindings = new ArrayList<>();
        for (Long userId : userIds) {
            for (Long menuId : menuIds) {
                bindings.add(new UserMenuBinding(userId, menuId));
            }
        }

        // 查询是否存在重复绑定
        List<UserMenuMapping> existingBindings = templateMapper.checkExistingBindings(bindings,templateId);

        if (!existingBindings.isEmpty()) {
            String conflictDetails = existingBindings.stream()
                    .map(binding -> String.format("用户: %s, 菜单: %s",
                            binding.getNickName(), binding.getMenuName()))
                    .collect(Collectors.joining("，"));

            throw new ServiceException("以下用户和菜单已绑定其他模板：" + conflictDetails);
        }
    }
    /**
     *校验模版名称
     */
    private void checkTemplateName(TemplateRequest templateRequest){
        LambdaQueryWrapper<Template> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Template::getTemplateName,templateRequest.getTemplateName());

        String templateId = templateRequest.getTemplateId();
        if(StringUtils.isNotEmpty(templateId)){
            queryWrapper.notIn(Template::getId,templateId);
        }

        if(templateMapper.selectCount(queryWrapper) > 0 ){
            throw new ServiceException("模板名称已存在，请选择其他名称");
        }
    }
    /**
     *新增模板明细
     */
    private void insertTemplateDetail (TemplateRequest templateRequest,Template template){

        String templateId = templateRequest.getTemplateId();
        //删除旧模板明细
        LambdaQueryWrapper<TemplateDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TemplateDetail::getTemplateId,templateId);
        templateDetailMapper.delete(queryWrapper);

        // 保存明细表
        for (TemplateDetailRequest detailRequest : templateRequest.getDetails()) {
            TemplateDetail detail = new TemplateDetail(IdUtils.fastSimpleUUID(),template.getId(),
                    detailRequest.getReviewerId(),detailRequest.getReviewerName(),detailRequest.getReviewOrder());
            templateDetailMapper.insert(detail);
        }
    }

    /**
     *新增模板菜单关联表
     */
    private void insertTemplateMenus (TemplateRequest templateRequest,Template template){

        String menuIds[] = templateRequest.getMenuIds().split(",");
        String templateId = template.getId() ;

        //删除原来的数据
        LambdaQueryWrapper<TemplateMenus> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TemplateMenus::getTemplateId,templateId);
        templateMenusMapper.delete(queryWrapper);

        //插入数据
        for(String menuId : menuIds){
            SysMenu sysMenu = sysMenuMapper.selectMenuByIdAndStatus(Long.valueOf(menuId));
            SysMenu sm = sysMenuMapper.selectMenuById(Long.valueOf(menuId));
            if(sysMenu == null){
                throw new ServiceException("菜单【"+sm.getMenuName()+"】已经停用，请重新选择菜单");
            }
            TemplateMenus templateMenus  = new TemplateMenus(IdUtils.fastSimpleUUID(),templateId,menuId);
            templateMenusMapper.insert(templateMenus);
        }
    }

}




